package com.op.teachingliteapp.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.op.teachingliteapp.R;
import com.op.teachingliteapp.bean.UserBean;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.database.dao.UserDao;
import com.op.teachingliteapp.fragment.dropdown.DropDownAdapter;
import com.op.teachingliteapp.service.LoginService;
import com.op.teachingliteapp.service.UserService;
import com.op.teachingliteapp.util.IntentUtils;
import com.op.teachingliteapp.util.SharedPreferencesUtils;
import com.op.teachingliteapp.util.StringUtils;
import com.op.teachingliteapp.util.ToastUtils;
import com.op.teachingliteapp.util.network.NetworkUtils;

/**
 * 登录界面
 * 
 * @author 陈宇瀚
 * 
 */
public class LoginActivity extends Activity {

	private static final String TAG = LoginActivity.class.getSimpleName();
	// TODO 要去掉静态，DropDownAdapter要用到
	public static EditText userNumInput, userPwdInput;
	public static PopupWindow popupWindow;
	public static ImageButton dropDown;
	private CheckBox autoLogin, savePassword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		setupViews();
	}

	private void setupViews() {
		userNumInput = (EditText) findViewById(R.id.user_id);
		userPwdInput = (EditText) findViewById(R.id.user_pwd);
		dropDown = (ImageButton) findViewById(R.id.dropdown_btn);
		autoLogin = (CheckBox) findViewById(R.id.login_quick_auto_login_btn);
		savePassword = (CheckBox) findViewById(R.id.login_save_pwd_btn);
		initLoginSettings();
	}

	/**
	 * 登录按钮监听
	 * 
	 * <ol>
	 * <li>无网络，有登录记录，跳转HomeActivity</li>
	 * <li>无网络，无登录记录，提示无网络错误</li>
	 * <li>有网络，联网登录</li>
	 * <li>有网络，网络异常，提示网络异常</li>
	 * </ol>
	 */
	public void loginClicked(View v) {
		String userNum = userNumInput.getText().toString();
		String userPwd = userPwdInput.getText().toString();

		// 输入用户名、密码为空
		if (TextUtils.isEmpty(userNum) || TextUtils.isEmpty(userPwd)) {
			ToastUtils.show(this, R.string.tips_login_input_empty);
			return;
		}

		// 本地登录
		if (!NetworkUtils.isNetworkAvailable(this)) {
			if (isUserExist(userNum, userPwd)) {
				saveLoginSettings();
				IntentUtils.jump(LoginActivity.this, HomeActivity.class);
				finish();
			} else {
				ToastUtils.show(this, R.string.tips_login_fail_net_disconnected);
			}
			return;
		}

		// 联网登录
		LoginService.syncLogin(userNum, userPwd, new Response.Listener<String>() {

			@Override
			public void onResponse(String response) {
				Log.i(TAG, response);
				handleLoginResponse(response);
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e(TAG, error.getMessage(), error);
				ToastUtils.show(LoginActivity.this, R.string.tips_net_error);
			}
		});
	}

	/**
	 * 处理联网登录响应
	 */
	private void handleLoginResponse(String response) {
		// 获取数据为空
		if (StringUtils.isEmptyOrStringNull(response)) {
			ToastUtils.show(this, R.string.tips_server_get_empty);
			return;
		}

		LoginService loginService = new LoginService(this, response);
		if (loginService.isSyncLogin()) {
			loginService.saveData();
			saveLoginSettings();
			IntentUtils.jump(LoginActivity.this, HomeActivity.class);
			finish();
		} else {
			ToastUtils.show(LoginActivity.this, R.string.tips_login_fail);
		}

	}

	/**
	 * 下拉按钮监听
	 * 
	 */
	public void dropDownBtnClicked(View v) {
		// 更新autoLogin、下拉按钮和savePassword的状态
		boolean isDropDownButtonClicked = SharedPreferencesUtils.getPreference().getBoolean(
				Common.Prefs.DROP_DOWN_BUTTON_CONDITION, false);
		if (!isDropDownButtonClicked) {
			dropDown.setBackgroundResource(R.drawable.btn_login_drop_down_selected);
			// 点击后的状态存进SharedPreference
			Map<String, Object> prefsMap = new HashMap<String, Object>();
			prefsMap.put(Common.Prefs.DROP_DOWN_BUTTON_CONDITION, true);
			SharedPreferencesUtils.put(LoginActivity.this, prefsMap);

			UserDao userDao = new UserDao(LoginActivity.this);
			ArrayList<UserBean> userList = new ArrayList<UserBean>();
			userList = userDao.getAllUser();
			showPopupWindow(userNumInput, userList);
		} else {
			dropDown.setBackgroundResource(R.drawable.btn_login_drop_down_normal);
			Map<String, Object> prefsMap = new HashMap<String, Object>();
			prefsMap.put(Common.Prefs.DROP_DOWN_BUTTON_CONDITION, false);
			SharedPreferencesUtils.put(LoginActivity.this, prefsMap);
		}
	}

	/**
	 * 用户名历史的下拉菜单
	 * 
	 * @param view
	 * @param userList
	 */
	private void showPopupWindow(View view, ArrayList<UserBean> userList) {

		final DropDownAdapter adapter = new DropDownAdapter(LoginActivity.this, userList);
		// 一个自定义的布局，作为显示的内容
		View contentView = LayoutInflater.from(LoginActivity.this).inflate(
				R.layout.drop_down_listview, null);

		popupWindow = new PopupWindow(contentView, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, true);
		// 设置SelectPicPopupWindow弹出窗体的宽
		popupWindow.setWidth(600);
		popupWindow.setTouchable(true);
		ListView dropDownListView = (ListView) contentView.findViewById(R.id.drop_down_listview);
		dropDownListView.setAdapter(adapter);

		// 点击外部，收起popupwindow
		popupWindow.setTouchInterceptor(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				dropDown.setBackgroundResource(R.drawable.btn_login_drop_down_normal);
				// 将下拉按钮的状态保存到SharedPreference
				Map<String, Object> prefsMap = new HashMap<String, Object>();
				prefsMap.put(Common.Prefs.DROP_DOWN_BUTTON_CONDITION, false);
				SharedPreferencesUtils.put(LoginActivity.this, prefsMap);
				return false;// 这里如果返回true的话，touch事件将被拦截,拦截后,PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
			}
		});

		// 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
		popupWindow.setBackgroundDrawable(getResources().getDrawable(R.color.white));

		popupWindow.showAsDropDown(view);
	}

	/**
	 * TODO 应该要有一张本地登录过的用户表，而不是和网上的下载下来的用户表进行比较
	 */
	private boolean isUserExist(String userNumber, String userPassword) {
		UserDao userDao = new UserDao(LoginActivity.this);
		UserBean userBean = userDao.getUserByUserNumber(userNumber);

		return userBean != null && userBean.getPassword().equals(userPassword);
	}

	/**
	 * 初始化登录控件设置
	 */
	private void initLoginSettings() {
		// 初始化自动登录按钮设置
		autoLogin.setChecked(LoginService.isAutoLogin());

		// 初始化用户名、密码、保存密码控件设置
		if (LoginService.isSavePwd()) {
			savePassword.setChecked(true);
			userNumInput.setText(UserService.getUserNumber());
			userPwdInput.setText(UserService.getUserPwd());
		}
	}

	/**
	 * 保存控件状态设置
	 */
	private void saveLoginSettings() {
		Editor editor = SharedPreferencesUtils.getEditor();
		editor.putBoolean(Common.Prefs.IS_AUTO_LOGIN, autoLogin.isChecked()); // 保存是否自动登录
		editor.putBoolean(Common.Prefs.IS_SAVE_PASSWORD, savePassword.isChecked()); // 保存是否记住密码
		editor.commit();
	}

}
